package com.xy.springboot.game.task.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.iohao.game.action.skeleton.core.flow.FlowContext;
import com.iohao.game.bolt.broker.client.kit.ExternalCommunicationKit;
import com.xy.springboot.game.common.data.LoginVerifyData;
import com.xy.springboot.game.common.data.TaskData;
import com.xy.springboot.game.common.data.UserLoginData;
import com.xy.springboot.game.common.enums.SpringGameCodeEnum;
import com.xy.springboot.game.task.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class TaskServiceImpl implements TaskService {
    private final String key = "game-task";
    @Override
    public UserLoginData login(LoginVerifyData loginVerifyData, FlowContext flowContext) {
        log.info("LoginVerify : {}", loginVerifyData);
        String token = loginVerifyData.token;
        //SpringGameCodeEnum.USER_LOGIN_EXPIRE.assertTrue(!JWTUtil.verify(token, key.getBytes(StandardCharsets.UTF_8)));
        JWT jwt = JWTUtil.parseToken(token);

        Long userId = Long.parseLong(String.valueOf(jwt.getPayload().getClaim("userId").toString()));
        log.info("userId : {}", userId);
        SpringGameCodeEnum.USER_NOT_EXIST.assertNonNull(userId);
        boolean existUser = ExternalCommunicationKit.existUser(userId);
        SpringGameCodeEnum.USER_ONLINE.assertTrue(!existUser);
        UserLoginData userLoginData = new UserLoginData();
        userLoginData.userId = userId;
        userLoginData.userName = RandomUtil.randomString(6);
        userLoginData.phone = RandomUtil.randomNumbers(11);
        userLoginData.headImg = "https://www.baidu.com";
        userLoginData.tenantId = "1";
        // 绑定 userId，表示登录
        boolean success = flowContext.bindingUserId(userId);
        SpringGameCodeEnum.LOGIN_ERROR.assertTrue(success);
        flowContext.getHeadMetadata().setAttachmentData(JSONUtil.toJsonPrettyStr(userLoginData).getBytes(StandardCharsets.UTF_8));
        return userLoginData;
    }

    @Override
    public List<TaskData> getTaskList(FlowContext flowContext) {
        List<TaskData> taskDataList = new ArrayList<>();
        for (int i = 0; i < 2; i++) {
            TaskData taskData =  new TaskData();
            taskData.id = Long.parseLong(String.valueOf(i));
            taskData.name = "任务" + i;
            taskData.description = "任务" + i + "描述";
            taskData.reward = (double) i;
            taskData.userId = 1L+ i;
            taskData.userName = RandomUtil.randomNumbers(6);
            ///taskData.userPhone = RandomUtil.randomNumbers(11);
            taskDataList.add(taskData);
        }
        return taskDataList;
    }
}
